<template>
  <div class="app-container home">
    <!-- {{firstFiveList}} -->
    <el-row :gutter="20">
      <el-col :span="8">
        <div ref="pieChart1" style="width: 400px; height: 350px; display: inline-block;"></div>
      </el-col>
      <el-col :span="8">
        <div ref="pieChart2" style="width: 400px; height: 350px; display: inline-block;"></div>
      </el-col>
      <el-col :span="8">
        <div ref="pieChart3" style="width: 400px; height: 350px; display: inline-block;"></div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="box">
          <div ref="lineChart" style="width: 90%; height: 400px;"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="box">
          <div ref="barChart" style="width: 90%; height: 400px; display: inline-block;"></div>
        </div>
      </el-col>
    </el-row>
    <div>
      
    </div>
    
  </div>
</template>

<script setup name="Index">
import { queryData } from "@/api/home";
import { nextTick, onMounted, ref } from 'vue';
import * as echarts from 'echarts';

const lineChart = ref(null);
const pieChart1 = ref(null);
const pieChart2 = ref(null);
const pieChart3 = ref(null);
const barChart = ref(null);
const customerSource = ref([])
const customerIndustry = ref([])
const warehouseStatusList = ref([])
const quarterlyTotalsList = ref([])
const totalRevenueList = ref([])
const firstFiveList = ref([])

const getData = (data) => {
    // 使用 reduce 方法将数据按月份分组，并进行拼接与计数
    const monthlyData = data.reduce((acc, current) => {
        const month = current.month;
        if (!acc[month]) {
            acc[month] = { name: '', value: 0 }; // 初始化每个月份的对象
        }
        // 拼接 name，计数 value
        acc[month].name += (acc[month].name ? ',' : '') + (current.name || '未知客户');
        acc[month].value += 1;
        return acc;
    }, {});

    // 将结果转换为数组形式，确保返回 12 个对象
    const result = Array.from({ length: 12 }, (_, index) => {
        const month = (index + 1).toString();
        return {
            name: monthlyData[month] ? monthlyData[month].name : '', // 如果没有数据则为空字符串
            value: monthlyData[month] ? monthlyData[month].value : 0  // 如果没有数据则为 0
        };
    });

    console.log(result);
    return result;
};
onMounted(async() => {

  queryData().then(res => {
    console.log(res);
    res.data.setCustomerIndustryList.forEach((item) =>{
      customerSource.value.push(item)
    })
    res.data.setCustomerSourceList.forEach((item) =>{
      customerIndustry.value.push(item);
    })
    
    console.log("仓库",res.data.setWarehouseStatusList);
    
    res.data.setWarehouseStatusList.forEach((item) =>{
      warehouseStatusList.value.push(item);
    })
    
    res.data.quarterlyTotalsList.forEach(element => {
      quarterlyTotalsList.value.push(element.q1Total)
      quarterlyTotalsList.value.push(element.q2Total)
      quarterlyTotalsList.value.push(element.q3Total)
      quarterlyTotalsList.value.push(element.q4Total)
    });

    res.data.totalRevenueList.forEach((item) =>{
      totalRevenueList.value.push(item.value)
    })
    let firstFiveData =  getData(res.data.firstFiveList)
    firstFiveData.forEach((item) =>{
      firstFiveList.value.push(item)
    })
    console.log(firstFiveList.value);
  });
  
   // 等待 DOM 更新后再初始化图表
   await nextTick();

    
  const chart = echarts.init(lineChart.value);
  const chart1 = echarts.init(pieChart1.value);
  const chart2 = echarts.init(pieChart2.value);
  const chart3 = echarts.init(pieChart3.value);


  const option = {
    title: {
      text: '季度营收图',
      left: 'left'
    },
    tooltip: {
      trigger: 'item', // 鼠标悬停显示提示
      formatter: '{a} <br/>{b}: {c}' // 提示的格式
    },
    xAxis: {
      type: 'category',
      data: ['一季度', '二季度', '三季度', '四季度']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '',
        type: 'line',
        data: quarterlyTotalsList.value,
        smooth: true,
        symbol: 'circle', // 数据点的样式，可以是圆形
        symbolSize: 8 // 数据点的大小
      },
    ]
  };



  const option1 = {
    title: { text: '客户来源分布图', left: 'center' },
    legend: {
      top: 'bottom'
    },
    tooltip: { trigger: 'item' },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        // dataView: { show: true, readOnly: false },
        // restore: { show: true },
        // saveAsImage: { show: true }
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: [30, 100],
        center: ['50%', '50%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 5
        },
        data: customerSource.value
      }
    ]
  };

  const option2 = {
    title: { text: '客户行业分布', left: 'center' },
    tooltip: { trigger: 'item' },
    series: [
      {
        name: '',
        type: 'pie',
        radius: '50%',
        data:customerIndustry.value
      },

    ]
  };

  const option3 = {
    title: { text: '仓库类型占比类型', left: 'center' },
    tooltip: { trigger: 'item' },
    series: [
      {
        name: '',
        type: 'pie',
        radius: '50%',
        data:warehouseStatusList.value
      }
    ]
  };



   // 初始化柱状图
  const barChartInstance = echarts.init(barChart.value);

  const barOption = {
    title: { text: '优质客户信息图', left: 'left' },
    tooltip: {
        trigger: 'item', // 鼠标悬停时触发的类型
        formatter: function (params) {
          console.log(params);
          let result = '';
          if(params.seriesName === '优质客户'){
              result += `优质客户数: ${params.value}<br/>${params.name}`;
          }else{
            result = `${params.name} - 总营收: ${params.value}<br/>`
          }
            
            return result;
        }
    },
    legend: {
      data: ['总营收', '优质客户'] // 添加图例
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总营收',
        type: 'bar',
        data: totalRevenueList.value,
        itemStyle: {
          color: '#5470C6' // 总营收颜色
        }
      },
      {
        name: '优质客户',
        type: 'bar',
        data: firstFiveList.value,
        itemStyle: {
          color: '#91CC75' // 新增客户数颜色
        },
      },
    ]
  };
  
  setTimeout(() => {
    console.log(barOption);
    
    chart.setOption(option);
    chart1.setOption(option1);
    chart2.setOption(option2);
    chart3.setOption(option3); 
    barChartInstance.setOption(barOption);
  }, 1000);
});

</script>

<style scoped lang="scss">
// .box{
//   display: flex;
//   justify-content: center;
// }
</style>

